package com.gohi.main.wxpay.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import org.jdom.JDOMException;
import com.gohi.core.web.action.BaseAction;

import com.gohi.main.store.service.ICommentService;
import com.gohi.main.user.hbm.ShopgooOrder;
import com.gohi.main.util.StringUtil;




import com.gohi.main.wxpay.api.RequestHandler;
import com.gohi.main.wxpay.api.WxPayUtil;
import com.gohi.main.wxpay.api.util.WxApi;
import com.gohi.main.wxpay.api.util.XMLUtil;

public class Payction extends BaseAction {

	
	// 订单信息
	private ShopgooOrder order;
	// 订单的基本信息
	private ICommentService commentService;
	public String msg(){
		String type =this.getRequest().getParameter("type");
		String msg ="0";
		if(type!=null){
			if( type.equals("ok")){
				msg="充值成功！";
			}else if (type.equals("fail")){
				msg="对不起交易失败";
			}
		
		}
		this.getRequest().setAttribute("t", type);//消息的类型
		this.getRequest().setAttribute("msg", msg);//提示的信息
		return "msg";
	}
	public String index()  throws IOException, JDOMException{
		if(order==null ){
			this.alert="订单参数错误！";
			this.url="../index.do";
			return "ERROR";
		}
		String code = this.getRequest().getParameter("code");
	
		String openid = "olkcGj6Dh2z3NYcHqCFA7HvEuNzE";
		openid=	this.getSession().getAttribute("openid").toString();
		if(code!=null){
			String urls = WxApi.getFenCode(WxPayUtil.WX_APPID,
					WxPayUtil.WXAppSecret, code);
			JSONObject jsonObject = WxApi.httpsRequest(urls, "GET", null);
			openid=jsonObject.getString("openid");
			System.err.println(openid);	
		}
		RequestHandler reqHandler = new RequestHandler(this.getRequest(),
				this.getResponse());
		reqHandler.setParameter("appid", WxPayUtil.WX_APPID);

		reqHandler.setParameter("mch_id", WxPayUtil.WXMchid); // 商户号

		// reqHandler.setParameter("device_info", "");

		reqHandler.setParameter("nonce_str",
				StringUtil.getDate("yyyMMddhhmmss")); // 随机字符串
		reqHandler.setParameter("body", order.getItem_name()); // 商品描述
		
		reqHandler.setParameter("out_trade_no", order.getOrder_id()+""); // 商家订单号
		int d = (int) (100 * Double.parseDouble(order.getPrice()));
	    reqHandler.setParameter("total_fee", d+""); // 商品金额,以分为单位
		//reqHandler.setParameter("total_fee", "1"); // 商品金额,以分为单位
		reqHandler.setParameter("spbill_create_ip", "127.0.0.1"); // 用户的公网ip
		reqHandler.setParameter("notify_url", WxPayUtil.WXNotify);
		reqHandler.setParameter("trade_type", "JSAPI");
		// ------------需要进行用户授权获取用户openid-------------
		reqHandler.setParameter("openid", openid);
		// reqHandler.setParameter("product_id ", "");
		String requestUrl = reqHandler.getRequestURL();
		// requestUrl就是xml格式的string了
		// 那么，如何提交呢。下面是我的提交数据的方法。
		URL url = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(30000); // 设置连接主机超时（单位：毫秒)
		conn.setReadTimeout(30000); // 设置从主机读取数据超时（单位：毫秒)
		conn.setDoOutput(true); // post请求参数要放在http正文内，顾设置成true，默认是false
		conn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true
		conn.setUseCaches(false); // Post 请求不能使用缓存
		// 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.setRequestMethod("POST");// 设定请求的方法为"POST"，默认是GET
		conn.setRequestProperty("Content-Length", requestUrl.length() + "");
		String encode = "utf-8";
		OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(),
				encode);
		out.write(requestUrl.toString());
		out.flush();
		out.close();
		String result = WxPayUtil.getOut(conn);

		//System.err.println(result);

		Map<String, String> map = XMLUtil.doXMLParse(result);
		// 跳转到支付页面
		SortedMap<Object, Object> params = new TreeMap<Object, Object>();
		params.put("appId", WxPayUtil.WX_APPID);
		params.put("timeStamp", Long.toString(new Date().getTime()));
		params.put("nonceStr", map.get("nonce_str"));
		params.put("package", "prepay_id=" + map.get("prepay_id"));
		params.put("signType", "MD5");
		String paySign = WxPayUtil.createSign("UTF-8", params);
		params.put("packageValue", "prepay_id=" + map.get("prepay_id"));// 这里弄个packageValue，是方便ajax传值到页面中package是js的关键字出错
		params.put("paySign", paySign);
		//params.put("sendUrl","http://183.33.212.175:8016/wxweb/contents/config/pay_success.jsp");
		String json = JSONObject.fromObject(params).toString();
		this.alert = json;
		return "index";
	}
	
	//充值成功进入的地方
	@SuppressWarnings("unused")
	public void success() throws IOException, JDOMException {
		// 支付成功进入的地址\
		//System.err.println("支付成功！");
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();
		InputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		String result = new String(outSteam.toByteArray(), "utf-8");
		Map<Object, Object> map = XMLUtil.doXMLParse(result);
		//遍历参数
		/*	for (Object keyValue : map.keySet()) {
			System.out.println(keyValue + "=" + map.get(keyValue));
		}*/
		if(map!=null && map.get("result_code").toString().trim().equals("SUCCESS")){
			String tempid  = map.get("out_trade_no").toString();
			logger.info("微信支付成功,订单号:"+map.get("out_trade_no"));
			int lin = commentService.changeOrders(tempid,"1",map.get("openid").toString());//线上
			response.getWriter().write(WxPayUtil.setXML("SUCCESS", ""));
		
		}else{
			logger.error("微信支付参数错误");
		}
		/*生成的订单号：0wx2015031610212406
		~~~~~~~~~~~~~~~~付款成功~~~~~~~~~
		is_subscribe=Y
		appid=wx45f453e9ec7552fa
		fee_type=CNY
		nonce_str=20150316102125
		out_trade_no=0wx2015031610212406
		transaction_id=1001770050201503160032194619
		trade_type=JSAPI
		result_code=SUCCESS
		sign=B56FCE97D326F980D88FC4E0AB710711
		mch_id=1232869702
		total_fee=1
		time_end=20150316102151
		openid=o0GPNjiXysVLjgDcXS8XRthOiKwU
		bank_type=CFT
		return_code=SUCCESS
		cash_fee=1*/
		// 返回支付成功

	}

	

	/**
	 * 报警异常接口
	 * 
	 * @throws IOException
	 */
	public void fail() throws IOException {
		logger.error("收到微信返回的参数错误");
		//this.getResponse().getWriter().print("支付失败");
	}

	
	public ShopgooOrder getOrder() {
		return order;
	}
	public void setOrder(ShopgooOrder order) {
		this.order = order;
	}
	public ICommentService getCommentService() {
		return commentService;
	}
	public void setCommentService(ICommentService commentService) {
		this.commentService = commentService;
	}
	
	
	
	

}
